import { Component, OnInit, Injectable, Injector } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router,ActivatedRoute } from '@angular/router';

import { UUID } from 'angular2-uuid';

import { OrgService } from '../../../@core/service/person-select-service/api/org.service';
import { CAPTCHAService } from '../../../@core/service/login-service/api/cAPTCHA.service';
import { OAuth2Service } from '../../../@core/service/login-service/api/oAuth2.service';
import { SYSTEMService } from '../../../@core/service/login-service/api/sYSTEM.service';
import { MissionService } from '../../../@core/service/subscribe/mission.service';
//rxjs
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  public url:any;
  public title:any = "用户登录";
  public validateText:any = "提示消息";
  public circleSrc = "circle.png";
  public session = sessionStorage;
  public user:any = {
    grantType: "password",
    userName: null,
    password: null,
    verificationCode: "",
    uuid: "",
    scope: 'all'
  };
  public loginFlag = false;
  public jumpFlag = false;
  public loginText = "登录";
  public uuid: any;
  protected show = false;
  public tips =  {
    type: 'success',
    msg: "success",
    hiddenFlag: false
  }
  subscription: Subscription;

  constructor(public injector: Injector,
    private http: HttpClient,
    private captchasService: CAPTCHAService,
    private oAuth2Service: OAuth2Service,
    private router: Router,
    private active:ActivatedRoute,
    private orgService: OrgService,
    private systemService: SYSTEMService,
    private missionService: MissionService,
  ) {
    this.subscription = this.missionService.missionConfirmed$.subscribe(res => {
      if (res['to'] == 'login') {
        this.loginFlag = res['data'];
        this.loginText = "登录";
      }
    })
  }

  ngOnInit() {
    // 获取验证码
    this.uuid = UUID.UUID();
    this.captchasService.captchaGet(this.uuid).subscribe((res) => {
      this.url = res['data']['captcha'];
    }, (error) => {
      
    });
    document.body.onkeydown = () => {
      let timer = setTimeout(()=>{}, 500);
      clearTimeout(timer);
      if (this.router.url == "/login" && event['keyCode'] == "13") {
        this.checkCaptcha();
      }
    }
  }
  
  // 验证验证码
  checkCaptcha() {
    if(this.user.verificationCode==null||this.user.verificationCode==""){
      this.showAlert('请输入验证码', 'error', true);
      return;
    }
    this.loginFlag = true;
    this.loginText = "登录中..."
    this.captchasService.captchaCheckPost(this.uuid, this.user.verificationCode).subscribe(res => {
      if (res['rel']) {
        this.login();
      } else {
        this.loginFlag = false;
        this.loginText = "登录"
      }
    }, error => {
      this.flushCard();
      this.loginFlag = false;
      this.loginText = "登录"
    })
  }

  // 登录
  login() {

  
  


    if(this.user.userName == null || this.user.userName ==""){
      this.showAlert('请输入用户名', 'error', true);
    }else if(this.user.password == null||this.user.password == ""){
      this.showAlert('请输入密码', 'error', true);
    }else if(this.user.verificationCode==null||this.user.verificationCode==""){
      this.showAlert('请输入验证码', 'error', true);
    }else{
      this.user['uuid'] = this.uuid;
      this.loginText = "登录中..."
      this.oAuth2Service.authTokenPasswordPost({ 
          grantType: this.user.grantType,
          username:  this.user.userName,
          password:  this.user.password,
          scope:      this.user.scope,
          clientId:    'cms',
      }).subscribe((res) => {
        if (res['rel']) {
          for (let key in res['data']) {
            this.session.setItem(key, res['data'][key]);
          }
          // 登录成功之后获取用户资源
          let token = res['data']['accessToken'];
          this.getOrgData(token);
        } else {
          this.loginFlag = false;
          this.loginText = "登录";
        }
      }, (error) => {
        this.flushCard();
        this.loginFlag = false;
        this.loginText = "登录";
      });
    }
  }

  // 刷新验证码
  flushCard(): void {
    this.url = "";
    let olduuid = this.uuid;
    this.uuid = UUID.UUID().toString();
    this.captchasService.captchaRefreshPut(this.uuid, olduuid).subscribe((res) => {
      this.url = res['data']['captcha'];
    }, (error) => {
      this.loginFlag = false;
      this.loginText = "登录";
    });
  }

  // 获取组织架构信息
  getOrgData(token) {
    this.systemService.authOrgsGet(token).subscribe(res => {
      if (res['rel']) {
        this.session.setItem('areaData', JSON.stringify(res['data']));
        this.getAuthData(token);
      } else {
        this.loginFlag = false;
        this.loginText = "登录";
      }
    }, error => {
      this.loginFlag = false;
      this.loginText = "登录";
    });
  }

  // 获取登录用户角色，权限，机构，职位
  getAuthData(token) {
    this.systemService.authUserPost(token).subscribe(res => {
      if (res['rel']) {
        for (let key in res['data']) {
          var itemData = res['data'][key];
          var item = typeof(itemData) != 'string'? JSON.stringify(itemData) : itemData;
          this.session.setItem(key, item);
        }
        let userid = res['data']['userId'];
        this.router.navigate(['main']);
        this.loginFlag = false;
        this.loginText = "登录中"; 
        // this.getPermission(userid);
      } else {
        this.loginFlag = false;
        this.loginText = "登录";
      }
    }, error => {
      this.loginFlag = false;
      this.loginText = "登录";
    })
  }

  // 清空input的值
  clear(key) {
    this.user[key] = "";
  }

  toggleMsg() {
    this.show = !this.show;
  }

  showAlert(msg:string, type:string, hiddenFlag: boolean) {
    this.tips.hiddenFlag = hiddenFlag;
    this.tips.msg = msg;
    this.tips.type = type;
    let timer;
    clearTimeout(timer);
    timer = setTimeout(()=>{
      this.tips.hiddenFlag = false;
    },1500)
  }
}
